<?php
declare (strict_types = 1);

namespace app\api\validate;

use think\facade\Request;

/**
 * 验证参数值为正整数的验证器
 * @author 聂哥<https://www.52document.com>
 * @date 2021/10/31
 */
class ParamMustBePostiveInt extends BaseValidate
{
    /**
     * 验证规则
     */
    protected $rule = [];

    /**
     * 验证信息
     */
    protected $message = [];

    /**
     * 验证的id属性
     */
    protected $attrName;

    public function __construct($attrName = 'id')
    {
        $this->rule    = [$attrName => 'require|isPositiveInteger'];
        $this->message = [
          $attrName.'.require' => "缺失参数：{$attrName}",
          $attrName.'.isPositiveInteger' => "{$attrName}必须是正整数"
        ];

        $this->attrName = $attrName;

        parent::__construct();
    }

    /**
     * 进行请求参数校验
     */
    public function paramCheck()
    {
        $value = Request::param($this->attrName);
        $data = [$this->attrName => $value];

        $result  = $this->check($data);
        if (!$result) {
            $e = new \app\api\exception\ParameterException([
                'msg' => $this->error,
            ]);
            throw $e;
        } else {
            return (int)$value;
        }
    }
}